class User < ActiveRecord::Base
  
  validates_presence_of :username, :email
  validates_uniqueness_of :username, :email
  validates_format_of :email, :with => /(.+)@(.+)\.(.{2})/, :message => " 输入的邮件地址必须是一个合法的邮件地址" 
  attr_accessor :password_confirmation
  validate :password_non_blank
  validates_confirmation_of :password
  
  has_many :word
  has_many :word_comment
  has_many :bookmarks
  has_many :learning_words, :class_name => "Word", :through => :bookmarks, :source => :word, :order => 'rating desc, bookmarks.updated_at desc'
  has_many :marked_comments, :class_name => "WordComment", :through => :users_comment, :source => :word_comment
  def password
    @password
  end
  
  def password=(pass)
    @password=pass
    return if pass.blank?    
    salt = [Array.new(6){rand(256).chr}.join].pack("m").chomp 
    self.password_salt, self.password_hash = salt, Digest::SHA256.hexdigest(pass + salt) 
  end
  
  def self.authenticate(username, password) 
    user = User.find(:first, :conditions => [ ' username = ? ' , username]) 
    if user.blank? || Digest::SHA256.hexdigest(password + user.password_salt) != user.password_hash 
      user = nil
    end
    logger.info "User is nil ? " + (user == nil).to_s 
    user 
  end 
    
  private
    def password_non_blank
      errors.add_to_base("Missing password") if password_hash.blank?
    end
end
